package com.gitee.kamismile.stoneEureka.client.handler;

import com.gitee.kamismile.gatewayAgent.client.service.imp.GateWayClientHelper;
import com.gitee.kamismile.gatewayAgent.protobuf.Message;
import com.gitee.kamismile.stone.commmon.util.JsonUtil;
import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import com.gitee.kamismile.stoneEureka.client.common.ClientChannel;
import com.google.protobuf.ByteString;
import io.netty.channel.Channel;
import com.gitee.kamismile.stoneEureka.client.EurekaClientConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@Component
public class EureKaClientGateWayClientHelper extends GateWayClientHelper {
    @Autowired
    private EurekaClientConstant eurekaClientConstant;
    private Channel channel;
    protected final Logger logger = LoggerFactory.getLogger("bLog");

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void afterConnect() {
        logger.info("channel--" + this.channel);
        EurekaClientConstant.AppProvider app = eurekaClientConstant.getApp().get("application");
        if (ValueUtils.isNotNull(app.getAppPath())) {
            new Timer(true).schedule(new TimerTask() {
                @Override
                public void run() {
                    String tokenCmd = "app@register@token";
                    Map<String, Object> map = JsonUtil.json2Map(JsonUtil.toJson(app));
                    String token = ClientChannel.token.get("token");
                    if (StringUtils.isNoneBlank(token)) {
                        map.put("token", token);
                    }
                    sendMessage(tokenCmd, JsonUtil.toJson(map), 1L, "1");
                }
            }, TimeUnit.SECONDS.toMillis(3));
        }
    }


    public void sendMessage(String cmdInfo, String data, Long seq, String router) {
        Message.RouterMessage.Builder msg = Message.RouterMessage.newBuilder();
        Message.RouterRequest.Builder request = Message.RouterRequest.newBuilder();
        request.setSeq(seq);
        request.setRouter(router);
        Message.Command.Builder cmd = Message.Command.newBuilder();
        cmd.setCommand(cmdInfo);
        request.setCmd(cmd);
        request.setSerializedData(ByteString.copyFrom(data.getBytes()));
        msg.addRequest(request);
        channel.writeAndFlush(msg);
    }
}
